//
//  MapVC.m
//  TongGuanLease
//
//  Created by Henghuitong on 2022/6/14.
//

#import "MapVC.h"

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
//#import <AMapLocationKit/AMapLocationKit.h>


#import "SearchBarDisplayCenter.h"

#import "MapResultsCell.h"
#import "MapResultsModel.h"
#import "MapSearchVC.h"
#import "LBXPermission.h"
#import "LBXPermissionSetting.h"

#define Text @"若地址不存在，您可手动输入地址"

@interface MapVC ()<QMUITableViewDelegate, QMUITableViewDataSource,SearchBarDisplayCenterDelegate,MAMapViewDelegate,AMapSearchDelegate,UITextFieldDelegate>

//AMapLocationManagerDelegate
@property (nonatomic, strong) SearchBarDisplayCenter *searchBar;
@property (nonatomic, strong) QMUIButton *searchBtn;
@property (nonatomic, strong) QMTableView *tableView;


@property (nonatomic, strong) MAMapView *mapview;
@property (nonatomic, strong) AMapSearchAPI *searchAPI;

//@property (nonatomic,strong) AMapLocationManager *locationManager;//定位管理


@property (nonatomic, assign) BOOL isOld;
@property (nonatomic,assign) CLLocationCoordinate2D oldPointCoordinate;
@property (nonatomic,assign) CLLocationCoordinate2D currentCoordinate;


@property (nonatomic, strong) NSMutableArray *addressArray;
@property (nonatomic, assign) NSInteger selectedAddressIndex;
//@property (nonatomic, copy) NSString *keywords;

@property (nonatomic, assign) BOOL isClickTable;


//@property (nonatomic, assign) BOOL isSearchBack;

@property (nonatomic, assign) BOOL isLocation;


@property (nonatomic, copy) NSString *enterAddress;

@end

@implementation MapVC

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    
    [self setNavStyleWhiteAndBackBtn];
    [self setRightBarButtonTitle:@"确认" selector:@selector(clickconfirmResultsAction)];
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"所在地区";

    self.selectedAddressIndex = 0;
    
//    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
//    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    
   
    [AMapSearchAPI updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [AMapSearchAPI updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    
    
    [self setupUI];
    
    
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
    [self.mapview setZoomLevel:18 animated:YES];
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    if(self.isLocation == NO) {
        self.mapview.showsUserLocation = YES;
        self.mapview.userTrackingMode = MAUserTrackingModeFollow;
        //通冠机械的经纬度
        [self.mapview setCenterCoordinate:CLLocationCoordinate2DMake(34.754444076858256, 113.40826913417681)];
        self.currentCoordinate = CLLocationCoordinate2DMake(34.754444076858256, 113.40826913417681);
        //周边搜索
        [self searchPoiByCenterCoordinate];
        [LBXPermission authorizeWithType:LBXPermissionType_Location completion:^(BOOL granted, BOOL firstTime) {
            if (!granted) {
                
                [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"您好，需要获取您当前的位置选择保养地址" cancel:@"暂不打开" setting:@"设置"];
                
            } else if(!firstTime) {

            }
            
        }];
        
    }
        
   
//    if(self.isLocation == NO)
//    {
//        //开始定位
//        [self.locationManager startUpdatingLocation];
//
//    }
  
    
}



#pragma mark -UI

- (void)setupUI
{
    [self setupSearchView];
    [self setupMapView];
    [self setupMapResultsTableView];
}

- (void)setupSearchView {
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioWidth(50))];
    searchView.backgroundColor = UIColorForBackground;
    [self.view addSubview:searchView];
 
    


    self.searchBar = [[SearchBarDisplayCenter alloc] init];
    self.searchBar.placeholderStr = @"搜索地点";
    self.searchBar.delegate = self;
    [searchView addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(TableViewSpace);
        make.right.mas_equalTo(-TableViewSpace);
        make.height.mas_equalTo(RatioWidth(50));
    }];
    
        QMUIButton *searchBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        searchBtn.backgroundColor = [UIColor clearColor];
        [searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
        [searchView addSubview:searchBtn];
        self.searchBtn = searchBtn;
        [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.left.top.bottom.equalTo(searchView);
        }];
}

- (void)setupMapView
{
    self.mapview = [[MAMapView alloc] init];
    self.mapview.delegate = self;
//    self.mapview.desiredAccuracy = kCLLocationAccuracyBest;
  
    [self.view addSubview: self.mapview];
    
    [self.mapview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.searchBar.mas_bottom).offset(RatioWidth(10));
        make.height.mas_equalTo((CGRectGetHeight(self.view.frame) - RatioWidth(50))/2.0 - RatioWidth(80));
    }];
    
}


-(void)setupMapResultsTableView
{
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo( self.mapview.mas_bottom);
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(IS_IPHONEX?-20:0);
    }];
    
    
}


#pragma mark -点击事件
//确认地址返回
- (void)clickconfirmResultsAction
{

    if(self.addressArray.count == 0)
    {
        [TGProgressHUD showHUDTip:@"请选择地点"];
        return;
    }
    if(self.clickclickconfirmResultsBlock)
    {
        MapResultsModel *model = [self.addressArray objectAtIndex:self.selectedAddressIndex];
        self.clickclickconfirmResultsBlock(model);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)searchAction
{
    MapSearchVC *vc = [[MapSearchVC alloc] init];
    [self pushViewController:vc complent:nil];
    
    WEAKSELF(weakSelf)
    [vc setClickSearchResultsBlock:^(MapResultsModel * _Nonnull model) {
        weakSelf.currentCoordinate = CLLocationCoordinate2DMake(model.coordinate.latitude, model.coordinate.longitude);
       
//        self.isSearchBack = YES;
        
        weakSelf.isOld = NO;
        //周边搜索
        [weakSelf searchPoiByCenterCoordinate];

    }];
}

#pragma mark -Other methods
- (void)searchWithIsHidKeybord:(BOOL)isHideKeybord {

}


//发起地图周边搜索
- (void)searchPoiByCenterCoordinate
{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    
    request.location = [AMapGeoPoint locationWithLatitude:self.currentCoordinate.latitude longitude:self.currentCoordinate.longitude];
    /* 按照距离排序. */
    request.sortrule            = 0;
    request.requireExtension    = YES;
    
    [self.searchAPI AMapPOIAroundSearch:request];

    
}

//添加标注
-(void)addPointAnnotation:(CLLocationCoordinate2D)currentCoordinate
{
    [self.mapview removeAnnotations:self.mapview.annotations];

    
    MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
    point.coordinate = CLLocationCoordinate2DMake(currentCoordinate.latitude,currentCoordinate.longitude);
    point.lockedToScreen = YES;
    point.lockedScreenPoint = CGPointMake(self.mapview.bounds.size.width / 2.0, self.mapview.bounds.size.height / 2.0) ;
//    point.lockedScreenPoint = self.mapview.center;
    NSLog(@"添加标注====%f ==%f",point.coordinate.latitude,point.coordinate.longitude);

    [self.mapview addAnnotation:point];
    //设置地图
    [self.mapview setZoomLevel:18 animated:YES];
    [self.mapview selectAnnotation:point animated:YES];
    [self.mapview setCenterCoordinate:currentCoordinate animated:NO];
    
}

//反地理编码
- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];

    regeo.location                    = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension            = YES;
    
    [self.searchAPI AMapReGoecodeSearch:regeo];
    
    
}


#pragma mark - SearchBarDisplayCenterDelegate
-(void)getSearchKeyWord:(NSString *)searchWord
{
    NSLog(@"输入文本：%@",searchWord);
//    self.keywords = searchWord;
//    [self searchPoiByCenterCoordinate];

}

#pragma mark - TableViewDelegate, TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return RatioWidth(80);
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return RatioWidth(50);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    UITextField *tf = [[UITextField alloc]init];
    tf.backgroundColor = [UIColor clearColor];
    tf.textColor =  [UIColor colorWithHexString:@"#333333"];;;
    tf.font = TGBlodAFont(16);
    tf.textAlignment = NSTextAlignmentLeft;
    tf.delegate = self;
    tf.placeholder =Text;
    [view addSubview:tf];
    [tf mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(RatioWidth(16));
        make.right.mas_equalTo(RatioWidth(16));
        make.top.bottom.right.mas_equalTo(0);
    }];
    return view;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    MapResultsCell *cell = [MapResultsCell mapResultsCellWithTableView:tableView cellForRowAtIndexPath:indexPath];
    
    cell.model = [self.addressArray objectAtIndex:indexPath.row];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];

    
    self.selectedAddressIndex = indexPath.row;
    self.isClickTable = YES;
    for (int i = 0; i < self.addressArray.count; i++) {
       
        MapResultsModel *model = self.addressArray[i];
        
        if(i == self.selectedAddressIndex)
        {
            model.isCheck = YES;
         
            [self addPointAnnotation:CLLocationCoordinate2DMake(model.coordinate.latitude, model.coordinate.longitude)];

        }else
        {
            model.isCheck = NO;
        }
    }
    [self.tableView reloadData];
    
    
    
    
    
    
}

#pragma mark - mapview delegate
/**
 * @brief 地图区域即将改变时会调用此接口
 * @param mapView 地图View
 * @param animated 是否动画
 */
- (void)mapView:(MAMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    NSLog(@"地图区域即将改变时");
    if(mapView.annotations.count != 0)
    {
        self.isOld = YES;
        MAPointAnnotation *pin =  mapView.annotations[0];
        self.oldPointCoordinate = pin.coordinate;
        NSLog(@"地图区域即将改变时pin====%f ==%f",pin.coordinate.latitude,pin.coordinate.longitude);
        NSLog(@"地图区域即将改变时self.oldPointCoordinate====%f ==%f",self.oldPointCoordinate.latitude,self.oldPointCoordinate.longitude);

    }else
    {
        self.isOld = NO;
    }

}

/**
 * @brief 地图将要发生移动时调用此接口
 * @param mapView 地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapWillMoveByUser:(BOOL)wasUserAction;
{
 
    NSLog(@"地图将要发生移动时");
}
/**
 * @brief 地图移动结束后调用此接口
 * @param mapView 地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
    
    NSLog(@"地图移动结束后");
   
}

/**
 * @brief 地图缩放结束后调用此接口
 * @param mapView       地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction
{
    NSLog(@"地图缩放结束后");

   
}

//地图区域改变完成后会调用此接口
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
   
    NSLog(@"地图区域改变完成后");
    
    if(mapView.annotations.count != 0)
    {
        
        MAPointAnnotation *pin1 =  mapView.annotations[0];
//        MAPointAnnotation *pin =   self.mapview.annotations[0];
//        NSLog(@"地图区域改变完成后pin====%f ==%f",pin.coordinate.latitude,pin.coordinate.longitude);

        NSLog(@"地图区域改变完成后pin1====%f ==%f",pin1.coordinate.latitude,pin1.coordinate.longitude);
        
    
        if(self.isOld == YES && self.oldPointCoordinate.latitude != pin1.coordinate.latitude && self.oldPointCoordinate.longitude != pin1.coordinate.longitude)
        {
            self.currentCoordinate = CLLocationCoordinate2DMake(pin1.coordinate.latitude, pin1.coordinate.longitude);

            [self searchPoiByCenterCoordinate];
            

        }else
        {
            NSLog(@"faadfa");
        }
    
        if(self.addressArray.count >0)
        {
//            MapResultsModel *model = self.addressArray[self.selectedAddressIndex];
            
//            if(model.coordinate.latitude == pin1.coordinate.latitude && model.coordinate.longitude == pin1.coordinate.longitude)
//            {
//                self.isClickTable = NO;
//            }else
//            {
//
//            }
//
//            if(model.coordinate.latitude != pin1.coordinate.latitude && model.coordinate.longitude != pin1.coordinate.longitude)
//            {
//                if(self.isClickTable == YES)
//                {
//                    self.currentCoordinate = CLLocationCoordinate2DMake(pin1.coordinate.latitude, pin1.coordinate.longitude);
//                    [self searchPoiByCenterCoordinate];
//                }
//
//
//            }
        }
       
        
    }
    
}

- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
//    MAAnnotationView *view = views[0];
//
//    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
//    if ([view.annotation isKindOfClass:[MAUserLocation class]])
//    {
//        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
////        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
////        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
//        pre.image = [UIImage imageNamed:@"map_location_icon"];
//        pre.showsAccuracyRing = NO;///精度圈是否显示，默认YES
//
////        pre.lineWidth = 3;
////        pre.lineDashPattern = @[@6, @3];
//
//        [self.mapview updateUserLocationRepresentation:pre];
//
//        view.calloutOffset = CGPointMake(0, 0);
//        view.canShowCallout = NO;
//        self.userLocationAnnotationView = view;
//    }
}
/**
 * @brief 根据anntation生成对应的View
 * @param mapView 地图View
 * @param annotation 指定的标注
 * @return 生成的标注View
 */
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{

    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        NSLog(@"MAPointAnnotation");

        static NSString *pointReuseIdentifier = @"pointReuseIdentifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIdentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIdentifier];
            
            annotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
            annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
            annotationView.draggable = NO;        //设置标注可以拖动，默认为NO
        }
        
        
        return annotationView;
    }
    
    return nil;
}

/**
 * @brief 拖动annotation view时view的状态变化，ios3.2以后支持
 * @param mapView 地图View
 * @param view annotation view
 * @param newState 新状态
 * @param oldState 旧状态
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view didChangeDragState:(MAAnnotationViewDragState)newState fromOldState:(MAAnnotationViewDragState)oldState
{
    NSLog(@"拖动annotation view时view的状态变化");
    
    if(newState == MAAnnotationViewDragStateEnding) {
      
//        CLLocationCoordinate2D coordinate = view.annotation.coordinate;
//        NSLog(@"拖动后坐标====%f  %f",coordinate.latitude, coordinate.longitude);
//
//        self.currentCoordinate = coordinate;
//
//        [self searchPoiByCenterCoordinate];

    }
    
    
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
//    NSLog(@"位置或者设备方向更新后调用此接口");
    NSLog(@"====%f  %f",userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    
        if(updatingLocation == YES)
        {
            if(self.isLocation == NO)
            {
                self.isLocation = YES;
                
                self.currentCoordinate   = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
                
                //周边搜索
                [self searchPoiByCenterCoordinate];
                
            
                self.mapview.showsUserLocation = NO;

            }
        }
    
//    if(updatingLocation == YES)
//    {
//        NSLog(@"------%f  %f",userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
//
//
//        self.currentCoordinate   = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
//
////        MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
////        point.coordinate = CLLocationCoordinate2DMake(self.mapview.userLocation.location.coordinate.latitude, self.mapview.userLocation.location.coordinate.longitude);
//////        point.lockedToScreen = YES;
//////        point.lockedScreenPoint = self.mapview.center;
////
////        [self.mapview addAnnotation:point];
////
////        [self searchPoiByCenterCoordinate];
//
//        self.mapview.showsUserLocation = NO;
//
//    }
    
}

//#pragma mark - AMapLocationManagerDelegate
//-(void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
//{
//
//}
//
////-(void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction
////{
////
////}
///* 当定位发生错误时，会调用代理的此方法 */
//- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
//{
//    //定位错误
//    NSLog(@"定位error = %@",error);
//}
//
///* 位置更新回调 */
//- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
//{
//    //经纬度
//    NSLog(@"location:{lat:%f; lon:%f}", location.coordinate.latitude, location.coordinate.longitude);
//
//    //中止定位
//    [self.locationManager stopUpdatingLocation];
//    self.isLocation = YES;
//
////    if(self.isSearchBack == NO)
////    {
////
////
////    }else
////    {
////        self.isSearchBack = NO;
////    }
//
//    self.currentCoordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
//    //周边搜索
//    [self searchPoiByCenterCoordinate];
//
//
////    [self addPointAnnotation:self.currentCoordinate];
//
//
//}



#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"error==%@",error);
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    NSLog(@"pois==%@",response.pois);
    if (response.pois.count == 0)
    {
        [TGProgressHUD showHUDTip:@"未搜索到相关结果"];
        
        self.selectedAddressIndex = 0;
        [self.addressArray removeAllObjects];
        [self.tableView reloadData];
        return;
    }
    

    
    if([request isKindOfClass:[AMapPOIKeywordsSearchRequest class]])
    {
        
    }else if([request isKindOfClass:[AMapPOIAroundSearchRequest class]])
    {
        
        
        if(self.addressArray.count != 0)
        {
            self.selectedAddressIndex = 0;
            [self.addressArray removeAllObjects];
        }
        

        
        NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
        NSLog(@"POI 搜索回调==%@",poiAnnotations);
        
        for (int i = 0; i < response.pois.count ; i ++)
        {
            AMapPOI *aPOI = response.pois[i];

            MapResultsModel *model = [[MapResultsModel alloc] init];
            if( i == 0)
            {
                model.isCheck = YES;
                
                if(self.isOld == NO)
                {
                    [self addPointAnnotation:CLLocationCoordinate2DMake(aPOI.location.latitude, aPOI.location.longitude)];
                    
                }
            }
            model.name = aPOI.name;
            model.address = aPOI.address;
            model.coordinate = CLLocationCoordinate2DMake(aPOI.location.latitude, aPOI.location.longitude);
            model.latitude = aPOI.location.latitude;
            model.longitude = aPOI.location.longitude;
            model.province =  aPOI.province;
            model.city = aPOI.city ;
            model.district = aPOI.district;
            
            model.pcode = aPOI.pcode;
            if (aPOI.adcode.length == 6) {
                model.citycode = [NSString stringWithFormat:@"%@00", [aPOI.adcode substringToIndex:4]];
            } else {
                model.citycode = aPOI.adcode;
            }
            model.adcode = aPOI.adcode;
            
            NSMutableString *address = [NSMutableString string];
            [address appendString:aPOI.province.length > 0 ? aPOI.province : @""];
            [address appendString:aPOI.city.length > 0 ? aPOI.city : @""];
            [address appendString:aPOI.district.length > 0 ? aPOI.district : @""];
            [address appendString:aPOI.address.length > 0 ? aPOI.address : @""];
            model.detailedAddress = address;
            [self.addressArray addObject:model];
       
        }
        [self.tableView reloadData];
        [self.tableView scrollToTopAnimated:NO];
    }
    
}

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
 
    NSLog(@"response===%@",response);
    AMapReGeocode *regeocode = response.regeocode;
    AMapAddressComponent *aPOI = regeocode.addressComponent;
    
    MapResultsModel *model = [[MapResultsModel alloc] init];
    model.name = self.enterAddress;
    model.address = regeocode.formattedAddress
    ;
    model.coordinate = CLLocationCoordinate2DMake(self.currentCoordinate.latitude, self.currentCoordinate.longitude);
    model.latitude = self.currentCoordinate.latitude;
    model.longitude = self.currentCoordinate.longitude;
    model.province =  aPOI.province;
    model.city = aPOI.city ;
    model.district = aPOI.district;
/*
 _pcode    NSTaggedPointerString *    @"410000"    0xb82ee20cf129f718
 _adcode    NSTaggedPointerString *    @"410182"    0xb82fe60c7129f718
 
 _adcode    NSTaggedPointerString *    @"410182"    0xb82fe60c7129f718
 */
//    model.pcode = aPOI.pcode;
    model.pcode = aPOI.adcode;
    model.citycode = aPOI.adcode;
    model.adcode = aPOI.adcode;
//
//    NSMutableString *address = [NSMutableString string];
//    [address appendString:aPOI.province.length > 0 ? aPOI.province : @""];
//    [address appendString:aPOI.city.length > 0 ? aPOI.city : @""];
//    [address appendString:aPOI.district.length > 0 ? aPOI.district : @""];
//    [address appendString:aPOI.address.length > 0 ? aPOI.address : @""];
    
    model.detailedAddress = regeocode.formattedAddress;
    
    [self.addressArray insertObject:model atIndex:0];
  
    self.selectedAddressIndex = 0;
    for (int i = 0; i < self.addressArray.count; i++) {
       
        MapResultsModel *model = self.addressArray[i];
        
        if(i == self.selectedAddressIndex)
        {
            model.isCheck = YES;
         
        }else
        {
            model.isCheck = NO;
        }
    }
    [self.tableView reloadData];
    [self.tableView scrollToTop];
    
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField;
{
    NSLog(@"textField==text====%@",textField.text);
    self.enterAddress =textField.text;
    
    [self searchReGeocodeWithCoordinate:self.currentCoordinate];

    
}

#pragma mark -
- (QMTableView*)tableView {
    if (!_tableView) {
        QMTableView *tb = [[QMTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tb.delegate = self;
        tb.dataSource = self;
        tb.backgroundColor = UIColorWhite;
        tb.separatorStyle = UITableViewCellSeparatorStyleNone;
        tb.showsVerticalScrollIndicator = NO;
        [tb registerClass:[MapResultsCell class] forCellReuseIdentifier:MapResultsCellID];
        tb.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
        tb.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TableViewSpace)];
    
        _tableView = tb;
    }
    return _tableView;
}

-(NSMutableArray *)addressArray
{
    
    if(!_addressArray)
    {
        _addressArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _addressArray;
    
}

//- (AMapLocationManager *)locationManager
//{
//    if (!_locationManager) {
//        _locationManager = [[AMapLocationManager alloc] init];
//        [_locationManager setDelegate:self];
//        if (@available(iOS 14.0, *)) {
//            _locationManager.locationAccuracyMode = AMapLocationReduceAccuracy;
//        } else {
//            // Fallback on earlier versions
//        }
//        [_locationManager setAllowsBackgroundLocationUpdates:YES];
//        //iOS 9（不包含iOS 9） 以前设置容许后台定位参数，保持不会被系统挂起
//        [_locationManager setPausesLocationUpdatesAutomatically:NO];
//
//        //iOS 9（包含iOS 9）以后新特性：将容许出现这种场景，同一app中多个locationmanager：一些只能在前台定位，另外一些可在后台定位，并可随时禁止其后台定位。
//        if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 9) {
//            _locationManager.allowsBackgroundLocationUpdates = YES;
//        }
//    }
//    return _locationManager;
//}

- (AMapSearchAPI *)searchAPI
{
    if (!_searchAPI) {
        _searchAPI = [[AMapSearchAPI alloc] init];
        _searchAPI.delegate = self;
    }
    return _searchAPI;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
